# -*- coding=utf-8 -*-
'''
Created on Aug 4, 2016

@author: corvo
'''

from datetime import datetime
from Basehandler import BaseHandler
from Database.tables import Express
from Utlis.ReturnCodeConfig import CodeTable
from Utlis.Helper import get_card

class SubmitHandler(BaseHandler):
    """
    提交的去快递请求在此处理, 提交成功后将会返回unix时间戳
    """

    def post(self):
        retjson = {'code':200, 'content': ''}
        # 读取post内容
        try:
            #_card_num  = self.get_argument('cardnumber')
            _uuid       = self.get_argument('uuid')
            _user_name  = self.get_argument('user_name')
            _user_phone = self.get_argument('user_phone')
            _sms_txt    = self.get_argument('sms_txt')
            _dest       = self.get_argument('dest')
            _arrival    = self.get_argument('arrival')
            _locate     = self.get_argument('locate')
            _weight     = self.get_argument('weight')
        except Exception as e:
            print (e)
            retjson['code'] = 300
            retjson['content'] = CodeTable[300]
            self.write_back(retjson)
            return
        
        _card_num = get_card(_uuid)
        
        if not _card_num:
            #print ("Wrong UUID")
            retjson['code'] = 301
            retjson['content'] = CodeTable[301]
            self.write_back(retjson)
            return
            
#        print ('card_num: ' + _card_num)
#        print ('user_name: ' + _user_name)
#        print ('user_phone: ' + _user_phone)
#        print ('smx_txt: ' + _sms_txt)
#        print ('dest: ' + _dest)
#        print ('arrival: ' + _arrival)
#        print ('locatet: ' + _locate)
#        print ('weight: ' + _weight)
#
#         try:
#             res = self.db.query(Express).one()
#         except:
#             retjson['code'] = 300
#             retjson['content'] = u'参数太少'
#             self.write_back(retjson)
#             return
#         
        _cur_time =  datetime.now() # 获取当前时间, 将会存入数据库

        express = Express(
            cardnum    = _card_num,
            #uuid      = _uuid,
            sms        = _sms_txt,
            user       = _user_name,
            phone      = _user_phone,
            dest       = _dest,
            arrival    = _arrival,
            locate     = _locate,
            weight     = _weight,
            submittime = _cur_time,
        )

        try:
            self.db.add(express)           
            self.db.commit()
        except Exception as e:
            print (e)
            retjson['code'] = 500
            retjson['content'] = CodeTable[500]
            self.write_back(retjson)
            return

        #print (res)
        suc = {'sub_time': _cur_time.strftime("%s")} # 返回unix时间戳

#        retjson['content'] = u'请求成功'
        retjson['content'] = suc
        self.write_back(retjson)
